package org.example.zpqy.controll;

import org.example.zpqy.service.PlantDiseaseDetectionService;
import org.example.zpqy.bean.RecognitionHistory;
import org.example.zpqy.repository.RecognitionHistoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 图片上传控制器
 */
@RestController
@RequestMapping("/api/images")
public class ApiAppToolsController {
    private static final Logger logger = LoggerFactory.getLogger(ApiAppToolsController.class);
    // 图片上传目录
    @Value("${image.upload.dir:uploads}")
    private String uploadDir;

    @Autowired
    private PlantDiseaseDetectionService plantDiseaseDetectionService;

    @Autowired
    private RecognitionHistoryRepository recognitionHistoryRepository;

    /**
     * 上传单张图片
     */
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<Map<String, Object>> uploadSingleImage(
            @RequestParam("file") MultipartFile file) {

        logger.info("Received image upload request. File name: {}", file.getOriginalFilename());
        logger.info("File content type: {}", file.getContentType());
        logger.info("File size: {} bytes", file.getSize());

        Map<String, Object> result = new HashMap<>();

        // 验证文件是否为空
        if (file.isEmpty()) {
            result.put("success", false);
            result.put("message", "请选择要上传的图片");
            return ResponseEntity.badRequest().body(result);
        }

        // 验证文件类型
        String contentType = file.getContentType();
        if (!isValidImageType(contentType)) {
            result.put("success", false);
            result.put("message", "请上传有效的图片文件（支持JPG、PNG、GIF、SVG）");
            return ResponseEntity.badRequest().body(result);
        }

        try {
            // 确保上传目录存在
            Path uploadPath = Paths.get(uploadDir).toAbsolutePath().normalize();
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
                logger.info("创建上传目录: {}", uploadPath);
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = getFileExtension(originalFilename);
            String fileName = UUID.randomUUID().toString() + "." + fileExtension;
            Path filePath = uploadPath.resolve(fileName);

            // 保存文件
            Files.write(filePath, file.getBytes());
            logger.info("文件保存路径: {}", filePath);

            // 调用本地模型进行病虫害分析
            String analysisResult = plantDiseaseDetectionService.callLocalModelWithImage(filePath.toString());

            // 处理过长的识别结果（截断或使用摘要）
            String resultToSave = analysisResult;
            if (analysisResult.length() > 65535) { // 超过MySQL TEXT类型最大长度
                resultToSave = analysisResult.substring(0, 65535) + "...";
                logger.warn("识别结果过长，已截断保存");
            }

            // 保存识别记录到数据库
            RecognitionHistory history = new RecognitionHistory();
            history.setResult(resultToSave);
            recognitionHistoryRepository.save(history);

            // 返回成功信息和图片URL
            result.put("success", true);
            result.put("message", "图片上传成功");
            result.put("fileName", fileName);
            result.put("url", "/api/images/" + fileName);
            result.put("analysisResult", analysisResult);

            return ResponseEntity.ok(result);
        } catch (IOException e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "图片上传失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "处理请求时发生错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }


    /**
     * 获取图片
     */
    @GetMapping("/{fileName}")
    public ResponseEntity<byte[]> getImage(@PathVariable String fileName) {
        try {
            Path filePath = Paths.get(uploadDir, fileName);

            // 安全检查：防止路径遍历攻击
            if (!isPathSafe(filePath)) {
                return ResponseEntity.notFound().build();
            }

            byte[] imageBytes = Files.readAllBytes(filePath);

            // 根据文件扩展名确定Content-Type
            String contentType = getContentType(fileName);

            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .body(imageBytes);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 验证文件类型是否为有效图片类型
     */
    private boolean isValidImageType(String contentType) {
        if (contentType == null) {
            return false;
        }
        return contentType.equals("image/jpeg") ||
                contentType.equals("image/png") ||
                contentType.equals("image/gif") ||
                contentType.equals("image/svg+xml");
    }

    /**
     * 根据文件名确定Content-Type
     */
    private String getContentType(String fileName) {
        if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
            return "image/jpeg";
        } else if (fileName.endsWith(".png")) {
            return "image/png";
        } else if (fileName.endsWith(".gif")) {
            return "image/gif";
        } else if (fileName.endsWith(".svg")) {
            return "image/svg+xml";
        }
        return "application/octet-stream";
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String fileName) {
        if (fileName == null) {
            return "";
        }
        int lastIndex = fileName.lastIndexOf('.');
        if (lastIndex == -1) {
            return "";
        }
        return fileName.substring(lastIndex + 1).toLowerCase();
    }

    /**
     * 安全检查：防止路径遍历攻击
     */
    private boolean isPathSafe(Path path) {
        try {
            Path uploadRoot = Paths.get(uploadDir).toAbsolutePath().normalize();
            Path resolvedPath = uploadRoot.resolve(path).toAbsolutePath().normalize();

            return resolvedPath.startsWith(uploadRoot);
        } catch (Exception e) {
            return false;
        }
    }
}